package com.zlm.tools.validation;

import cn.hutool.core.exceptions.ValidateException;
import com.zlm.tools.annotation.Length;
import com.zlm.tools.annotation.Max;
import com.zlm.tools.annotation.Min;

import java.lang.reflect.Field;

/**
 * {@code 校验器}
 *
 * @author zlm
 * @since 2025/5/30
 */
public class Validator {

    void validate(Object bean)throws Exception{
        Class<?> aClass = bean.getClass();

        for (Field field : aClass.getDeclaredFields()) {
            field.setAccessible(true);

            ValidatorChain chain = buildValidateChain(field);
            chain.vaildate(field.getName(),field.get(bean));

        }

    }

    private ValidatorChain buildValidateChain(Field field) {
        ValidatorChain chain = new ValidatorChain();
        Max max = field.getAnnotation(Max.class);
        if(max!=null){
            chain.addLastHandler(new MaxValidatorHandler(max.value()));
        }
        Min min = field.getAnnotation(Min.class);
        if(min!=null){
            chain.addLastHandler(new MinValidatorHandler(min.value()));
        }
        Length length = field.getAnnotation(Length.class);
        if(length!=null){
            chain.addLastHandler(new LengthValidatorHandler(length.min(),length.max()));
        }
        return chain;
    }

}
